<template>
  <view class="review-page">
    <!-- 服务信息预览 -->
    <view class="service-info-card">
      <image class="service-image" :src="orderInfo.serviceImage" mode="aspectFill"></image>
      <view class="service-details">
        <view class="title">{{ orderInfo.serviceName }}</view>
        <view class="desc">服务完成于 {{ orderInfo.completedTime }}</view>
      </view>
    </view>
    
    <!-- 评分区域 -->
    <view class="rating-section">
      <text class="label">服务评分</text>
      <!-- [重构] 自定义星级评分组件 -->
      <view class="custom-rating-container">
        <image
          v-for="star in 5"
          :key="star"
          class="star-image"
          :src="star <= rating ? '/static/icons/star-filled.svg' : '/static/icons/star-empty.svg'"
          @click="setRating(star)"
        ></image>
      </view>
      <text class="rating-text">{{ ratingText }}</text>
    </view>
    
    <!-- 评论内容 -->
    <view class="comment-section">
      <textarea
        v-model="comment"
        class="comment-textarea"
        placeholder="服务满足您的期望吗？说说您的感受，分享给其他用户吧~"
        maxlength="300"
      ></textarea>
      <view class="char-counter">{{ comment.length }}/300</view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="footer-btn-container">
       <button class="submit-btn" @click="submitReview" :disabled="!isSubmittable">发布评价</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

// ---- 响应式状态定义 ----
const orderInfo = reactive({
  orderId: null,
  serviceId: null,
  serviceName: '加载中...',
  serviceImage: '/static/icons/default-image.svg', // 默认占位图
  completedTime: '',
});

const rating = ref(5);
const comment = ref('');

// 评分文本映射
const ratingTexts = {
  1: '很差', 2: '差', 3: '一般', 4: '满意', 5: '强烈推荐',
};
const ratingText = computed(() => ratingTexts[rating.value] || '');
const isSubmittable = computed(() => comment.value.trim().length > 0);


// ---- API & 事件处理 ----

/**
 * @description 提交评价 (后端会自动更新订单状态)
 */
const submitReview = async () => {
  if (!isSubmittable.value) {
    return uni.showToast({ title: '请填写您的评价内容', icon: 'none' });
  }

  uni.showLoading({ title: '正在发布...' });

  try {
    // 构造请求参数
    const commentParams = {
      commentStar: rating.value,
      commentContent: comment.value,
    };
    
    // 按照后端最新的URL格式进行拼接
    const commentUrl = `/services/${orderInfo.serviceId}/setcomments/${orderInfo.orderId}`;
    
    await request({
      url: commentUrl,
      method: 'POST',
      data: commentParams,
    });
    
    console.log('评论提交成功，订单状态已由后端更新');

    uni.hideLoading();
    uni.showToast({ title: '评价成功！', icon: 'success' });

    // 延迟返回订单列表页
    // onShow 钩子会触发列表刷新，用户将看到更新后的订单状态
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);

  } catch (error) {
    uni.hideLoading();
    console.error("发布评价失败:", error);
  }
};

/**
 * @description 设置评分
 * @param {number} star - 选择的星级
 */
const setRating = (star) => {
  rating.value = star;
};

// ---- 生命周期钩子 ----
onLoad((options) => {
  if (options.order) {
    try {
      const orderData = JSON.parse(decodeURIComponent(options.order));
      console.log(orderData);
			
      orderInfo.orderId = orderData.id;
      orderInfo.serviceId = orderData.serviceId;
      orderInfo.serviceName = orderData.service;
      orderInfo.completedTime = orderData.orderEndTime || orderData.time;
      
      if (orderData.serviceHeadImg) {
        orderInfo.serviceImage = `${BASE_URL}${orderData.serviceImage}`;
      }
      
    } catch (e) {
      console.error("解析订单数据失败:", e);
      uni.showToast({ title: '订单信息错误', icon: 'error' });
    }
  } else {
    uni.showToast({ title: '缺少订单信息', icon: 'error' });
  }
});
</script>

<style lang="scss" scoped>
.review-page {
  background-color: $uni-bg-color; min-height: 100vh; padding: 30rpx;
}
.service-info-card {
  display: flex; gap: 30rpx; background-color: $uni-bg-color-white;
  padding: 30rpx; border-radius: 24rpx; margin-bottom: 30rpx;
  .service-image { width: 120rpx; height: 120rpx; border-radius: 16rpx; flex-shrink: 0; }
  .service-details {
    .title { font-size: 32rpx; font-weight: 500; margin-bottom: 10rpx; }
    .desc { font-size: 26rpx; color: $uni-text-color-light; }
  }
}
.rating-section {
  display: flex; align-items: center; background-color: $uni-bg-color-white;
  padding: 40rpx 30rpx; border-radius: 24rpx; margin-bottom: 30rpx;
  .label { font-size: 32rpx; font-weight: 500; margin-right: 20rpx; }
  .rating-text { font-size: 28rpx; color: $uni-color-warning; margin-left: auto; }
}

/* [新增] 自定义评分组件样式 */
.custom-rating-container {
  display: flex;
  align-items: center;
  gap: 10rpx;
  .star-image {
    width: 60rpx;
    height: 60rpx;
  }
}

.comment-section {
  background-color: $uni-bg-color-white; padding: 30rpx; border-radius: 24rpx;
  position: relative;
  .comment-textarea { width: 100%; height: 300rpx; font-size: 30rpx; line-height: 1.6; }
  .char-counter { position: absolute; bottom: 20rpx; right: 30rpx; font-size: 24rpx; color: $uni-text-color-light; }
}
.footer-btn-container { margin-top: 60rpx; }
.submit-btn {
  width: 100%; height: 90rpx; line-height: 90rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent); color: white;
  border-radius: 45rpx; font-size: 32rpx; font-weight: 500;
  &[disabled] { background: #E0E0E0; background-image: none; color: #A0A0A0; }
}
</style>